# Import contacts from Thunderbird to Apple mail client

import sys
import os
import re
import pprint

def process_file(fread, fwrite, format_list):
    res = []
    i_line = 1;
    for line in fread:
        if i_line == 1:
            fwrite.write(','.join(format_list).encode('utf8'))
            fwrite.write('\n'.encode('utf8'))
        line = line.strip()
        line_list = line.split(',')
        display_name = line_list[2].decode('gbk')
        idx = display_name.find('@')
        if idx > 0: # Trim whatever after '@'
            display_name = display_name[:idx]
        if display_name.isalpha(): # If Chinese name
            D = {'First Name': display_name[0], 
                'Last Name'  : display_name[1:], 
                'Phonetic first name' : line_list[0], 
                'Phonetic last name' : line_list[1], 
                'Nickname' : line_list[3], 
                'Primary Email' : line_list[4]}
        else:
            D = {'First Name': line_list[0], 
                'Last Name'  : line_list[1].upper(), 
                'Phonetic first name' : '', 
                'Phonetic last name' : '', 
                'Nickname' : '', 
                'Primary Email' : line_list[4]}
        line_write = ','.join([D['First Name'], D['Last Name'], 
                               D['Phonetic first name'],
                               D['Phonetic last name'],
                               D['Nickname' ],
                               D['Primary Email']])
        print line_write
        if not i_line == 1:
            fwrite.write(line_write.encode('utf8'))
            fwrite.write(u'\n')
        i_line = i_line + 1
    return res
    
def main():
    print 'Hello'
    
    format_list = ['First Name', 'Last Name', 
                   'Phonetic first name', 'Phonetic last name', 
                   'Nickname', 
                   'Primary Email']])
    read_file_name = 'a.csv'
    write_file_name = 'a1.csv'
    fread = open(read_file_name, 'r')
    fwrite = ospen(write_file_name, 'w')
    
    process_file(fread, fwrite, format_list)
    
    fread.close()
    fwrite.close()

main()